import { IBaseData } from '@amcax/base';
import { ColormapType, makeColorMap, ManagerId } from 'nextcae-base';
import { useRenderStore } from '../store';
import { nmAppErrorLog } from './logUtils';
import { VisualDataCloud } from '@/common/render';
import { handleGeometryRender } from '@/domain';

/**
 * 场数据格式，category为FIELD
 */
interface IFieldData extends VisualDataCloud {
  /**
   * 和对应id的SHAPE的points一一对应；
   * 目前只有标量场，后期扩展向量场等
   */
  field?: number[];
  /**
   * field最大最小值
   */
  extra: { max: number; min: number };
}
/**
 * 将数组归一化到 [0,1] 区间
 * @param arr 数组
 * @returns 归一化后的数组
 */
function normalizeTo01(
  arr: number[],
  minVal: number,
  maxVal: number,
): number[] {
  // 1. 如果所有元素相同，避免除零错误，直接返回全 0（或全 0.5）
  if (minVal === maxVal) {
    return arr.map(() => 0);
  }

  // 2. 使用 min-max 归一化公式 (x - min) / (max - min)
  return arr.map((x) => (x - minVal) / (maxVal - minVal));
}

/**
 * 渲染场模型
 */
export const renderFields = async (
  fields: IFieldData[],
  colorMap: ColormapType = 'jet',
) => {
  const colormap = makeColorMap(colorMap);
  const colormapLength = colormap.length;
  const itemSize = colormap[0].length;
  const mainRenderer = useRenderStore.getState().mainRenderer;
  const meshMgr = mainRenderer.getEntityManager(ManagerId.Mesh);
  if (!meshMgr) {
    nmAppErrorLog('mesh entity manager is null');
    return;
  }
  // 先渲染网格
  fields.forEach((field) => (field.category = 'MESH'));
  await handleGeometryRender(fields);

  // 再渲染场
  for (let i = 0; i < fields.length; i++) {
    const item = fields[i];
    const field = normalizeTo01(item.field, item.extra.min, item.extra.max);
    // 生成顶点颜色数据
    const vColors = field.flatMap((value: number) => {
      let index = Math.round(value * colormapLength);
      index = Math.max(0, Math.min(index, colormapLength - 1));
      return colormap[index];
    });
    console.log(vColors);
    meshMgr.applyVertexColors(item.id, vColors, itemSize);
  }
  mainRenderer.render();
};

/**
 * 清空场渲染（云图）
 */
export const clearFields = () => {
  const mainRenderer = useRenderStore.getState().mainRenderer;
  const meshMgr = mainRenderer.getEntityManager(ManagerId.Mesh);
  if (!meshMgr) {
    nmAppErrorLog('mesh entity manager is null');
    return;
  }
  meshMgr.removeVertexColors();
  mainRenderer.render();
};
